<template>
  <div class="permission-allocation-container">
    <!-- 页面头部区域 -->
    <div class="permission-header">
      <div class="header-content">
        <div class="ancient-title">权限分配管理</div>
        <div class="header-subtitle">阴曹地府 · 仙官权限配置与管理</div>
      </div>
      <div class="header-decoration">
        <div class="decoration-line"></div>
        <div class="decoration-symbol">🔐</div>
        <div class="decoration-line"></div>
      </div>
    </div>

    <!-- 路由信息显示 -->
    <div class="route-info">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <router-link to="/management">
            <ApartmentOutlined />
            机构管理
          </router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <router-link to="/management/official-position">
            <CrownOutlined />
            仙官职位管理
          </router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <SafetyOutlined />
          {{ $route.meta.title }}
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <!-- 权限统计卡片 -->
    <div class="stats-section">
      <a-row :gutter="[20, 20]" class="stats-grid">
        <a-col :xs="24" :sm="12" :xl="6">
          <div class="stat-card primary-stat">
            <div class="stat-icon">
              <SafetyOutlined />
            </div>
            <div class="stat-content">
              <div class="stat-title">权限组总数</div>
              <div class="stat-value">{{ permissionStats.totalGroups }}</div>
              <div class="stat-label">已配置</div>
            </div>
          </div>
        </a-col>

        <a-col :xs="24" :sm="12" :xl="6">
          <div class="stat-card judgment-stat">
            <div class="stat-icon">
              <UserOutlined />
            </div>
            <div class="stat-content">
              <div class="stat-title">已分配人员</div>
              <div class="stat-value">{{ permissionStats.assignedUsers }}</div>
              <div class="stat-label">仙官</div>
            </div>
          </div>
        </a-col>

        <a-col :xs="24" :sm="12" :xl="6">
          <div class="stat-card pending-stat">
            <div class="stat-icon">
              <ClockCircleOutlined />
            </div>
            <div class="stat-content">
              <div class="stat-title">待审批</div>
              <div class="stat-value">{{ permissionStats.pendingApprovals }}</div>
              <div class="stat-label">权限申请</div>
            </div>
          </div>
        </a-col>

        <a-col :xs="24" :sm="12" :xl="6">
          <div class="stat-card online-stat">
            <div class="stat-icon">
              <SecurityScanOutlined />
            </div>
            <div class="stat-content">
              <div class="stat-title">安全等级</div>
              <div class="stat-value">{{ permissionStats.securityLevel }}</div>
              <div class="stat-label">权限安全</div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 功能选项卡 -->
    <div class="tabs-section">
      <a-tabs v-model:activeKey="activeTab" type="card" @change="handleTabChange">
        <a-tab-pane key="groups" tab="权限组管理">
          <template #tab>
            <span>
              <TeamOutlined />
              权限组管理
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="matrix" tab="权限矩阵">
          <template #tab>
            <span>
              <TableOutlined />
              权限矩阵
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="approval" tab="权限审批">
          <template #tab>
            <span>
              <AuditOutlined />
              权限审批
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="monitor" tab="使用监控">
          <template #tab>
            <span>
              <MonitorOutlined />
              使用监控
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="security" tab="安全策略">
          <template #tab>
            <span>
              <SafetyOutlined />
              安全策略
            </span>
          </template>
        </a-tab-pane>
        <a-tab-pane key="reports" tab="权限报告">
          <template #tab>
            <span>
              <BarChartOutlined />
              权限报告
            </span>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 权限组管理内容 -->
    <div v-show="activeTab === 'groups'">
      <a-row :gutter="24">
        <!-- 左侧：权限组管理 -->
        <a-col :xs="24" :lg="12">
          <a-card title="权限组管理" :bordered="false">
            <template #extra>
              <a-button type="primary" size="small" @click="showAddGroupModal">
                <PlusOutlined />
                新增权限组
              </a-button>
            </template>

            <div class="permission-groups">
              <div v-for="group in permissionGroups" :key="group.id" class="group-item">
                <div class="group-header">
                  <div class="group-info">
                    <h4 class="group-name">{{ group.name }}</h4>
                    <p class="group-description">{{ group.description }}</p>
                  </div>
                  <div class="group-actions">
                    <a-dropdown>
                      <a-button type="text" size="small">
                        <MoreOutlined />
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item @click="editGroup(group)">
                            <EditOutlined />
                            编辑
                          </a-menu-item>
                          <a-menu-item @click="assignPermissions(group)">
                            <SettingOutlined />
                            配置权限
                          </a-menu-item>
                          <a-menu-item @click="viewGroupMembers(group)">
                            <TeamOutlined />
                            查看成员
                          </a-menu-item>
                          <a-menu-item @click="cloneGroup(group)">
                            <CopyOutlined />
                            复制权限组
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item @click="deleteGroup(group)" style="color: #ff4d4f">
                            <DeleteOutlined />
                            删除
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </div>
                </div>

                <div class="group-stats">
                  <a-row :gutter="16">
                    <a-col :span="8">
                      <div class="stat-item">
                        <div class="stat-number">{{ group.memberCount }}</div>
                        <div class="stat-label">成员数</div>
                      </div>
                    </a-col>
                    <a-col :span="8">
                      <div class="stat-item">
                        <div class="stat-number">{{ group.permissionCount }}</div>
                        <div class="stat-label">权限数</div>
                      </div>
                    </a-col>
                    <a-col :span="8">
                      <div class="stat-item">
                        <a-tag :color="group.status === 'active' ? 'green' : 'red'" size="small">
                          {{ group.status === 'active' ? '启用' : '禁用' }}
                        </a-tag>
                      </div>
                    </a-col>
                  </a-row>
                </div>

                <div class="group-permissions">
                  <a-tag v-for="permission in getGroupPermissions(group.id)" :key="permission" size="small" style="margin-bottom: 4px">
                    {{ getPermissionName(permission) }}
                  </a-tag>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>

        <!-- 右侧：个人权限分配 -->
        <a-col :xs="24" :lg="12">
          <a-card title="个人权限分配" :bordered="false">
            <template #extra>
              <a-space>
                <a-button size="small" @click="showBatchAssignModal">
                  <UsergroupAddOutlined />
                  批量分配
                </a-button>
                <a-input-search v-model:value="userSearchText" placeholder="搜索仙官" style="width: 200px" @search="searchUsers" />
              </a-space>
            </template>

            <div class="user-permission-list">
              <div v-for="user in filteredUsers" :key="user.id" class="user-item">
                <div class="user-info">
                  <a-avatar :src="user.avatar" size="large">
                    {{ user.name.charAt(0) }}
                  </a-avatar>
                  <div class="user-details">
                    <h4 class="user-name">{{ user.name }}</h4>
                    <p class="user-position">{{ user.position }} - {{ getDepartmentName(user.department) }}</p>
                    <div class="user-groups">
                      <a-tag v-for="groupId in user.groups" :key="groupId" size="small" color="blue">
                        {{ getGroupName(groupId) }}
                      </a-tag>
                    </div>
                  </div>
                </div>

                <div class="user-actions">
                  <a-button type="link" size="small" @click="editUserPermissions(user)">
                    <SettingOutlined />
                    配置权限
                  </a-button>
                  <a-button type="link" size="small" @click="viewUserPermissions(user)">
                    <EyeOutlined />
                    查看详情
                  </a-button>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 权限矩阵内容 -->
    <div v-show="activeTab === 'matrix'">
      <a-card title="权限矩阵管理" :bordered="false">
        <template #extra>
          <a-space>
            <a-button type="primary" @click="exportPermissionMatrix">
              <ExportOutlined />
              导出矩阵
            </a-button>
            <a-button @click="refreshMatrix">
              <ReloadOutlined />
              刷新矩阵
            </a-button>
          </a-space>
        </template>

        <div class="matrix-controls">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-select v-model:value="matrixFilter.department" placeholder="选择部门" style="width: 100%" allow-clear>
                <a-select-option value="all">全部部门</a-select-option>
                <a-select-option v-for="dept in departments" :key="dept.id" :value="dept.id">
                  {{ dept.name }}
                </a-select-option>
              </a-select>
            </a-col>
            <a-col :span="8">
              <a-select v-model:value="matrixFilter.group" placeholder="选择权限组" style="width: 100%" allow-clear>
                <a-select-option value="all">全部权限组</a-select-option>
                <a-select-option v-for="group in permissionGroups" :key="group.id" :value="group.id">
                  {{ group.name }}
                </a-select-option>
              </a-select>
            </a-col>
            <a-col :span="8">
              <a-select v-model:value="matrixFilter.permission" placeholder="选择权限类型" style="width: 100%" allow-clear>
                <a-select-option value="all">全部权限</a-select-option>
                <a-select-option v-for="perm in permissionTypes" :key="perm.key" :value="perm.key">
                  {{ perm.title }}
                </a-select-option>
              </a-select>
            </a-col>
          </a-row>
        </div>

        <div class="permission-matrix">
          <a-table :columns="matrixColumns" :data-source="filteredMatrixData" :pagination="false" :scroll="{ x: 1200 }" size="small">
            <template #headerCell="{ column }">
              <div class="matrix-header">
                <component :is="column.icon" v-if="column.icon" />
                <span>{{ column.title }}</span>
              </div>
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'user'">
                <div class="user-cell">
                  <a-avatar :src="record.avatar" size="small">
                    {{ record.name.charAt(0) }}
                  </a-avatar>
                  <div class="user-info">
                    <div class="user-name">{{ record.name }}</div>
                    <div class="user-role">{{ record.position }}</div>
                  </div>
                </div>
              </template>

              <template v-else-if="column.key && column.key.startsWith('perm_')">
                <div class="permission-cell">
                  <a-switch :checked="hasPermission(record.id, column.key.replace('perm_', ''))" @change="togglePermission(record.id, column.key.replace('perm_', ''), $event)" size="small" />
                </div>
              </template>

              <template v-else-if="column.dataIndex === 'actions'">
                <a-space>
                  <a-button type="link" size="small" @click="editMatrixRow(record)">
                    <EditOutlined />
                  </a-button>
                  <a-button type="link" size="small" @click="viewMatrixDetail(record)">
                    <EyeOutlined />
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </div>
      </a-card>
    </div>

    <!-- 权限审批内容 -->
    <div v-show="activeTab === 'approval'">
      <a-card title="权限审批流程" :bordered="false">
        <template #extra>
          <a-space>
            <a-button type="primary" @click="showApprovalConfigModal">
              <SettingOutlined />
              审批配置
            </a-button>
            <a-button @click="exportApprovalData">
              <ExportOutlined />
              导出审批记录
            </a-button>
          </a-space>
        </template>

        <a-row :gutter="24">
          <a-col :span="16">
            <div class="approval-workflow">
              <h4>审批流程</h4>
              <div class="workflow-steps">
                <div v-for="(step, index) in approvalSteps" :key="step.id" class="workflow-step">
                  <div class="step-number">{{ index + 1 }}</div>
                  <div class="step-content">
                    <div class="step-title">{{ step.title }}</div>
                    <div class="step-description">{{ step.description }}</div>
                    <div class="step-approvers">
                      <a-tag v-for="approver in step.approvers" :key="approver" size="small">
                        {{ approver }}
                      </a-tag>
                    </div>
                  </div>
                  <div v-if="index < approvalSteps.length - 1" class="step-connector"></div>
                </div>
              </div>
            </div>

            <div class="approval-list">
              <h4>待审批申请</h4>
              <a-table :columns="approvalColumns" :data-source="approvalRequests" :pagination="{ pageSize: 10 }" size="small">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'status'">
                    <a-tag :color="getApprovalStatusColor(record.status)">
                      {{ getApprovalStatusText(record.status) }}
                    </a-tag>
                  </template>
                  <template v-else-if="column.key === 'priority'">
                    <a-tag :color="getPriorityColor(record.priority)">
                      {{ getPriorityText(record.priority) }}
                    </a-tag>
                  </template>
                  <template v-else-if="column.key === 'actions'">
                    <a-space>
                      <a-button type="link" size="small" @click="approveRequest(record)">
                        <CheckOutlined />
                        审批
                      </a-button>
                      <a-button type="link" size="small" @click="viewApprovalDetail(record)">
                        <EyeOutlined />
                        详情
                      </a-button>
                    </a-space>
                  </template>
                </template>
              </a-table>
            </div>
          </a-col>

          <a-col :span="8">
            <div class="approval-stats">
              <h4>审批统计</h4>
              <div class="stats-grid">
                <div class="stat-card">
                  <div class="stat-number">{{ approvalStats.pending }}</div>
                  <div class="stat-label">待审批</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number">{{ approvalStats.approved }}</div>
                  <div class="stat-label">已通过</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number">{{ approvalStats.rejected }}</div>
                  <div class="stat-label">已拒绝</div>
                </div>
                <div class="stat-card">
                  <div class="stat-number">{{ approvalStats.expired }}</div>
                  <div class="stat-label">已过期</div>
                </div>
              </div>
            </div>

            <div class="approval-rules">
              <h4>审批规则</h4>
              <div class="rules-list">
                <div v-for="rule in approvalRules" :key="rule.id" class="rule-item">
                  <div class="rule-title">{{ rule.title }}</div>
                  <div class="rule-description">{{ rule.description }}</div>
                  <div class="rule-actions">
                    <a-button type="link" size="small" @click="editRule(rule)">编辑</a-button>
                  </div>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-card>
    </div>

    <!-- 使用监控内容 -->
    <div v-show="activeTab === 'monitor'">
      <a-card title="权限使用监控" :bordered="false">
        <template #extra>
          <a-space>
            <a-range-picker v-model:value="monitorDateRange" @change="updateMonitorData" />
            <a-button @click="exportMonitorData">
              <ExportOutlined />
              导出监控数据
            </a-button>
          </a-space>
        </template>

        <a-row :gutter="24">
          <a-col :span="12">
            <div class="usage-chart">
              <h4>权限使用频率</h4>
              <div ref="usageChartRef" class="chart-container"></div>
            </div>
          </a-col>

          <a-col :span="12">
            <div class="access-trend">
              <h4>访问趋势分析</h4>
              <div ref="accessTrendChartRef" class="chart-container"></div>
            </div>
          </a-col>
        </a-row>

        <div class="monitoring-table">
          <h4>权限使用记录</h4>
          <a-table :columns="monitorColumns" :data-source="monitoringData" :pagination="{ pageSize: 10 }" size="small">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'result'">
                <a-tag :color="record.result === 'success' ? 'green' : 'red'">
                  {{ record.result === 'success' ? '成功' : '失败' }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'riskLevel'">
                <a-tag :color="getRiskLevelColor(record.riskLevel)">
                  {{ getRiskLevelText(record.riskLevel) }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </div>
      </a-card>
    </div>

    <!-- 安全策略内容 -->
    <div v-show="activeTab === 'security'">
      <a-card title="权限安全策略" :bordered="false">
        <template #extra>
          <a-space>
            <a-button type="primary" @click="showSecurityConfigModal">
              <SettingOutlined />
              安全配置
            </a-button>
            <a-button @click="scanSecurityRisks">
              <ScanOutlined />
              风险扫描
            </a-button>
          </a-space>
        </template>

        <a-row :gutter="24">
          <a-col :span="16">
            <div class="security-policies">
              <h4>安全策略列表</h4>
              <a-table :columns="securityColumns" :data-source="securityPolicies" :pagination="{ pageSize: 8 }" size="small">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'status'">
                    <a-tag :color="record.status === 'active' ? 'green' : 'red'">
                      {{ record.status === 'active' ? '启用' : '禁用' }}
                    </a-tag>
                  </template>
                  <template v-else-if="column.key === 'severity'">
                    <a-tag :color="getSeverityColor(record.severity)">
                      {{ getSeverityText(record.severity) }}
                    </a-tag>
                  </template>
                  <template v-else-if="column.key === 'actions'">
                    <a-space>
                      <a-button type="link" size="small" @click="editSecurityPolicy(record)">编辑</a-button>
                      <a-button type="link" size="small" @click="testSecurityPolicy(record)">测试</a-button>
                    </a-space>
                  </template>
                </template>
              </a-table>
            </div>
          </a-col>

          <a-col :span="8">
            <div class="security-status">
              <h4>安全状态</h4>
              <div class="status-indicators">
                <div class="status-item">
                  <div class="indicator" :class="{ 'indicator-green': securityStatus.overall === 'good' }"></div>
                  <div class="status-label">整体安全</div>
                  <div class="status-value">{{ securityStatus.overall }}</div>
                </div>
                <div class="status-item">
                  <div class="indicator" :class="{ 'indicator-yellow': securityStatus.vulnerabilities > 0 }"></div>
                  <div class="status-label">安全漏洞</div>
                  <div class="status-value">{{ securityStatus.vulnerabilities }}</div>
                </div>
                <div class="status-item">
                  <div class="indicator" :class="{ 'indicator-red': securityStatus.risks > 0 }"></div>
                  <div class="status-label">安全风险</div>
                  <div class="status-value">{{ securityStatus.risks }}</div>
                </div>
              </div>
            </div>

            <div class="security-alerts">
              <h4>安全警报</h4>
              <div class="alerts-list">
                <div v-for="alert in securityAlerts" :key="alert.id" class="alert-item">
                  <div class="alert-icon">
                    <ExclamationCircleOutlined />
                  </div>
                  <div class="alert-content">
                    <div class="alert-title">{{ alert.title }}</div>
                    <div class="alert-time">{{ alert.time }}</div>
                  </div>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-card>
    </div>

    <!-- 权限报告内容 -->
    <div v-show="activeTab === 'reports'">
      <a-card title="权限分析报告" :bordered="false">
        <template #extra>
          <a-space>
            <a-button type="primary" @click="generateReport">
              <FileTextOutlined />
              生成报告
            </a-button>
            <a-button @click="exportAllReports">
              <ExportOutlined />
              导出报告
            </a-button>
          </a-space>
        </template>

        <a-row :gutter="24">
          <a-col :span="12">
            <div class="permission-distribution">
              <h4>权限分布统计</h4>
              <div ref="permissionDistributionChartRef" class="chart-container"></div>
            </div>
          </a-col>

          <a-col :span="12">
            <div class="usage-analytics">
              <h4>使用情况分析</h4>
              <div ref="usageAnalyticsChartRef" class="chart-container"></div>
            </div>
          </a-col>
        </a-row>

        <div class="report-summary">
          <h4>权限概况</h4>
          <a-row :gutter="24">
            <a-col :span="6">
              <div class="summary-card">
                <div class="summary-title">总权限数</div>
                <div class="summary-value">{{ reportData.totalPermissions }}</div>
                <div class="summary-trend">
                  <ArrowUpOutlined style="color: #52c41a" />
                  <span>较上月增长 {{ reportData.permissionGrowth }}%</span>
                </div>
              </div>
            </a-col>
            <a-col :span="6">
              <div class="summary-card">
                <div class="summary-title">活跃用户</div>
                <div class="summary-value">{{ reportData.activeUsers }}</div>
                <div class="summary-trend">
                  <ArrowUpOutlined style="color: #52c41a" />
                  <span>较上月增长 {{ reportData.userGrowth }}%</span>
                </div>
              </div>
            </a-col>
            <a-col :span="6">
              <div class="summary-card">
                <div class="summary-title">权限使用率</div>
                <div class="summary-value">{{ reportData.usageRate }}%</div>
                <div class="summary-trend">
                  <ArrowDownOutlined style="color: #ff4d4f" />
                  <span>较上月下降 {{ reportData.usageDecline }}%</span>
                </div>
              </div>
            </a-col>
            <a-col :span="6">
              <div class="summary-card">
                <div class="summary-title">安全评分</div>
                <div class="summary-value">{{ reportData.securityScore }}</div>
                <div class="summary-trend">
                  <ArrowUpOutlined style="color: #52c41a" />
                  <span>较上月提升 {{ reportData.securityImprovement }}分</span>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-card>
    </div>

    <!-- 权限组编辑弹窗 -->
    <a-modal v-model:open="groupModalVisible" :title="groupModalTitle" @ok="handleGroupSubmit" @cancel="handleGroupCancel" width="600px">
      <a-form ref="groupFormRef" :model="groupForm" :rules="groupRules" layout="vertical">
        <a-form-item label="权限组名称" name="name">
          <a-input v-model:value="groupForm.name" placeholder="请输入权限组名称" />
        </a-form-item>

        <a-form-item label="权限组描述" name="description">
          <a-textarea v-model:value="groupForm.description" placeholder="描述权限组的用途和适用场景" :rows="3" />
        </a-form-item>

        <a-form-item label="权限组类型" name="type">
          <a-select v-model:value="groupForm.type" placeholder="选择权限组类型">
            <a-select-option value="system">系统权限组</a-select-option>
            <a-select-option value="department">部门权限组</a-select-option>
            <a-select-option value="custom">自定义权限组</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="优先级" name="priority">
          <a-input-number v-model:value="groupForm.priority" :min="1" :max="100" style="width: 100%" />
        </a-form-item>

        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="groupForm.status">
            <a-radio value="active">启用</a-radio>
            <a-radio value="inactive">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 权限配置弹窗 -->
    <a-modal v-model:open="permissionModalVisible" title="权限配置" @ok="handlePermissionSubmit" @cancel="handlePermissionCancel" width="800px">
      <div v-if="selectedGroup">
        <h4>为权限组 "{{ selectedGroup.name }}" 配置权限</h4>

        <a-tree v-model:checkedKeys="checkedPermissions" :tree-data="permissionTree" checkable :default-expand-all="true" />

        <div class="permission-templates">
          <h5>权限模板</h5>
          <a-space>
            <a-button size="small" @click="applyPermissionTemplate('basic')">基础权限</a-button>
            <a-button size="small" @click="applyPermissionTemplate('advanced')">高级权限</a-button>
            <a-button size="small" @click="applyPermissionTemplate('admin')">管理员权限</a-button>
          </a-space>
        </div>
      </div>
    </a-modal>

    <!-- 用户权限配置弹窗 -->
    <a-modal v-model:open="userPermissionModalVisible" title="用户权限配置" @ok="handleUserPermissionSubmit" @cancel="handleUserPermissionCancel" width="700px">
      <div v-if="selectedUser">
        <h4>为 "{{ selectedUser.name }}" 配置权限</h4>

        <a-tabs>
          <a-tab-pane key="groups" tab="权限组分配">
            <a-checkbox-group v-model:value="userGroupSelection">
              <a-row>
                <a-col :span="12" v-for="group in permissionGroups" :key="group.id">
                  <a-checkbox :value="group.id">
                    {{ group.name }}
                    <a-tag size="small" style="margin-left: 8px">{{ group.permissionCount }}项权限</a-tag>
                  </a-checkbox>
                </a-col>
              </a-row>
            </a-checkbox-group>
          </a-tab-pane>

          <a-tab-pane key="individual" tab="个人特殊权限">
            <a-tree v-model:checkedKeys="userIndividualPermissions" :tree-data="permissionTree" checkable :default-expand-all="true" />
          </a-tab-pane>

          <a-tab-pane key="restrictions" tab="权限限制">
            <a-form layout="vertical">
              <a-form-item label="访问时间限制">
                <a-time-range-picker v-model:value="userRestrictions.timeRange" />
              </a-form-item>
              <a-form-item label="IP地址限制">
                <a-input v-model:value="userRestrictions.ipRestriction" placeholder="输入允许的IP地址或IP段" />
              </a-form-item>
              <a-form-item label="权限有效期">
                <a-date-picker v-model:value="userRestrictions.expireDate" />
              </a-form-item>
            </a-form>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>

    <!-- 批量分配弹窗 -->
    <a-modal v-model:open="batchAssignModalVisible" title="批量权限分配" @ok="handleBatchAssign" @cancel="handleBatchAssignCancel" width="800px">
      <a-form layout="vertical">
        <a-form-item label="选择用户">
          <a-transfer v-model:target-keys="batchAssignForm.selectedUsers" :data-source="batchUserOptions" :titles="['可选用户', '已选用户']" :render="(item) => item.title" :list-style="{ width: '300px', height: '300px' }" />
        </a-form-item>

        <a-form-item label="分配权限组">
          <a-checkbox-group v-model:value="batchAssignForm.groups">
            <a-row>
              <a-col :span="12" v-for="group in permissionGroups" :key="group.id">
                <a-checkbox :value="group.id">{{ group.name }}</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>

        <a-form-item label="分配方式">
          <a-radio-group v-model:value="batchAssignForm.assignMode">
            <a-radio value="add">添加权限</a-radio>
            <a-radio value="replace">替换权限</a-radio>
            <a-radio value="remove">移除权限</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import {
  HomeOutlined,
  ApartmentOutlined,
  CrownOutlined,
  SafetyOutlined,
  UserOutlined,
  ClockCircleOutlined,
  SecurityScanOutlined,
  PlusOutlined,
  MoreOutlined,
  EditOutlined,
  SettingOutlined,
  TeamOutlined,
  DeleteOutlined,
  EyeOutlined,
  CopyOutlined,
  TableOutlined,
  AuditOutlined,
  MonitorOutlined,
  BarChartOutlined,
  UsergroupAddOutlined,
  ExportOutlined,
  ReloadOutlined,
  CheckOutlined,
  ScanOutlined,
  FileTextOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'

// 响应式数据
const activeTab = ref('groups')
const groupModalVisible = ref(false)
const permissionModalVisible = ref(false)
const userPermissionModalVisible = ref(false)
const batchAssignModalVisible = ref(false)
const userSearchText = ref('')
const selectedGroup = ref(null)
const selectedUser = ref(null)
const checkedPermissions = ref([])
const userGroupSelection = ref([])
const userIndividualPermissions = ref([])
const userRestrictions = ref({
  timeRange: null,
  ipRestriction: '',
  expireDate: null
})
const groupFormRef = ref()
const monitorDateRange = ref([])
const usageChartRef = ref(null)
const accessTrendChartRef = ref(null)
const permissionDistributionChartRef = ref(null)
const usageAnalyticsChartRef = ref(null)

// 权限统计
const permissionStats = reactive({
  totalGroups: 12,
  assignedUsers: 856,
  pendingApprovals: 23,
  securityLevel: 'AAA'
})

// 权限组表单
const groupForm = reactive({
  id: null,
  name: '',
  description: '',
  type: 'custom',
  priority: 50,
  status: 'active'
})

// 表单验证规则
const groupRules = {
  name: [{ required: true, message: '请输入权限组名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入权限组描述', trigger: 'blur' }],
  type: [{ required: true, message: '请选择权限组类型', trigger: 'change' }],
  priority: [{ required: true, message: '请设置优先级', trigger: 'blur' }]
}

// 批量分配表单
const batchAssignForm = reactive({
  selectedUsers: [],
  groups: [],
  assignMode: 'add'
})

// 矩阵过滤器
const matrixFilter = reactive({
  department: 'all',
  group: 'all',
  permission: 'all'
})

// 部门数据
const departments = ref([
  { id: 'first_court', name: '第一殿秦广王府' },
  { id: 'second_court', name: '第二殿楚江王府' },
  { id: 'third_court', name: '第三殿宋帝王府' },
  { id: 'fourth_court', name: '第四殿五官王府' },
  { id: 'fifth_court', name: '第五殿阎罗王府' }
])

// 权限组数据
const permissionGroups = ref([
  {
    id: 'admin',
    name: '系统管理员',
    description: '拥有系统最高权限，可进行所有操作',
    type: 'system',
    priority: 100,
    memberCount: 5,
    permissionCount: 15,
    status: 'active',
    permissions: ['system_admin', 'user_management', 'data_export', 'audit_log']
  },
  {
    id: 'judge',
    name: '审判官',
    description: '负责业力审判和生死裁决',
    type: 'department',
    priority: 90,
    memberCount: 45,
    permissionCount: 8,
    status: 'active',
    permissions: ['karma_judgment', 'manage_life_death', 'view_archives', 'edit_archives']
  },
  {
    id: 'clerk',
    name: '文书官',
    description: '负责档案管理和日常事务处理',
    type: 'department',
    priority: 70,
    memberCount: 156,
    permissionCount: 5,
    status: 'active',
    permissions: ['view_archives', 'edit_archives', 'report_view']
  },
  {
    id: 'guardian',
    name: '守护仙官',
    description: '负责轮回监护和安全保障',
    type: 'department',
    priority: 80,
    memberCount: 78,
    permissionCount: 6,
    status: 'active',
    permissions: ['reincarnation_control', 'salvation_approval', 'view_archives']
  }
])

// 用户数据
const users = ref([
  {
    id: 1,
    name: '秦广王',
    position: '第一殿主审',
    department: 'first_court',
    avatar: '',
    groups: ['admin', 'judge'],
    individualPermissions: []
  },
  {
    id: 2,
    name: '判官李明',
    position: '主审判官',
    department: 'first_court',
    avatar: '',
    groups: ['judge'],
    individualPermissions: ['schedule_management']
  },
  {
    id: 3,
    name: '文书张华',
    position: '高级文书',
    department: 'second_court',
    avatar: '',
    groups: ['clerk'],
    individualPermissions: []
  },
  {
    id: 4,
    name: '守护王刚',
    position: '守护队长',
    department: 'third_court',
    avatar: '',
    groups: ['guardian'],
    individualPermissions: ['user_management']
  }
])

// 权限树数据
const permissionTree = ref([
  {
    title: '档案管理',
    key: 'archives',
    children: [
      { title: '查看档案', key: 'view_archives' },
      { title: '编辑档案', key: 'edit_archives' },
      { title: '删除档案', key: 'delete_archives' }
    ]
  },
  {
    title: '生死管理',
    key: 'life_death',
    children: [
      { title: '生死管理', key: 'manage_life_death' },
      { title: '寿命调整', key: 'adjust_lifespan' },
      { title: '死亡记录', key: 'death_records' }
    ]
  },
  {
    title: '业力系统',
    key: 'karma',
    children: [
      { title: '业力审判', key: 'karma_judgment' },
      { title: '业力计算', key: 'karma_calculation' },
      { title: '业力报告', key: 'karma_reports' }
    ]
  },
  {
    title: '轮回系统',
    key: 'reincarnation',
    children: [
      { title: '轮回控制', key: 'reincarnation_control' },
      { title: '投胎安排', key: 'reincarnation_arrangement' },
      { title: '轮回历史', key: 'reincarnation_history' }
    ]
  },
  {
    title: '超度救赎',
    key: 'salvation',
    children: [
      { title: '超度审批', key: 'salvation_approval' },
      { title: '功德转移', key: 'merit_transfer' },
      { title: '救赎计划', key: 'redemption_plan' }
    ]
  },
  {
    title: '系统管理',
    key: 'system',
    children: [
      { title: '系统管理', key: 'system_admin' },
      { title: '用户管理', key: 'user_management' },
      { title: '数据导出', key: 'data_export' },
      { title: '审计日志', key: 'audit_log' },
      { title: '排班管理', key: 'schedule_management' },
      { title: '报表查看', key: 'report_view' }
    ]
  }
])

// 权限类型
const permissionTypes = ref([
  { key: 'archives', title: '档案管理' },
  { key: 'life_death', title: '生死管理' },
  { key: 'karma', title: '业力系统' },
  { key: 'reincarnation', title: '轮回系统' },
  { key: 'salvation', title: '超度救赎' },
  { key: 'system', title: '系统管理' }
])

// 矩阵列配置
const matrixColumns = ref([
  { title: '用户', dataIndex: 'user', key: 'user', width: 150, fixed: 'left' },
  { title: '查看档案', key: 'perm_view_archives', width: 100, icon: 'EyeOutlined' },
  { title: '编辑档案', key: 'perm_edit_archives', width: 100, icon: 'EditOutlined' },
  { title: '业力审判', key: 'perm_karma_judgment', width: 100, icon: 'AuditOutlined' },
  { title: '生死管理', key: 'perm_manage_life_death', width: 100, icon: 'FileTextOutlined' },
  { title: '轮回控制', key: 'perm_reincarnation_control', width: 100, icon: 'ReloadOutlined' },
  { title: '超度审批', key: 'perm_salvation_approval', width: 100, icon: 'CheckOutlined' },
  { title: '系统管理', key: 'perm_system_admin', width: 100, icon: 'SettingOutlined' },
  { title: '操作', dataIndex: 'actions', key: 'actions', width: 120, fixed: 'right' }
])

// 审批流程步骤
const approvalSteps = ref([
  {
    id: 1,
    title: '申请提交',
    description: '用户提交权限申请',
    approvers: ['申请人']
  },
  {
    id: 2,
    title: '部门审核',
    description: '部门主管进行初步审核',
    approvers: ['部门主管']
  },
  {
    id: 3,
    title: '安全审查',
    description: '安全部门进行风险评估',
    approvers: ['安全官']
  },
  {
    id: 4,
    title: '最终审批',
    description: '系统管理员最终审批',
    approvers: ['系统管理员']
  }
])

// 审批申请数据
const approvalRequests = ref([
  {
    id: 1,
    applicant: '张三',
    requestType: '权限申请',
    permission: '生死管理',
    reason: '工作需要',
    status: 'pending',
    priority: 'high',
    submitTime: '2024-01-15 10:30'
  },
  {
    id: 2,
    applicant: '李四',
    requestType: '权限变更',
    permission: '档案编辑',
    reason: '职务调整',
    status: 'approved',
    priority: 'medium',
    submitTime: '2024-01-14 14:20'
  }
])

// 审批列配置
const approvalColumns = ref([
  { title: '申请人', dataIndex: 'applicant', key: 'applicant', width: 100 },
  { title: '申请类型', dataIndex: 'requestType', key: 'requestType', width: 100 },
  { title: '权限名称', dataIndex: 'permission', key: 'permission', width: 120 },
  { title: '申请理由', dataIndex: 'reason', key: 'reason', width: 150 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '优先级', dataIndex: 'priority', key: 'priority', width: 100 },
  { title: '提交时间', dataIndex: 'submitTime', key: 'submitTime', width: 150 },
  { title: '操作', key: 'actions', width: 120 }
])

// 审批统计
const approvalStats = reactive({
  pending: 23,
  approved: 156,
  rejected: 12,
  expired: 5
})

// 审批规则
const approvalRules = ref([
  {
    id: 1,
    title: '高级权限审批',
    description: '涉及系统管理、数据导出等高级权限需要两级审批'
  },
  {
    id: 2,
    title: '跨部门权限审批',
    description: '跨部门权限申请需要双方部门主管同意'
  },
  {
    id: 3,
    title: '紧急权限审批',
    description: '紧急情况下可以申请临时权限，有效期24小时'
  }
])

// 监控数据
const monitoringData = ref([
  {
    id: 1,
    user: '张三',
    permission: '查看档案',
    action: '查看生死簿',
    time: '2024-01-15 10:30:25',
    result: 'success',
    ip: '192.168.1.100',
    riskLevel: 'low'
  },
  {
    id: 2,
    user: '李四',
    permission: '编辑档案',
    action: '修改转世记录',
    time: '2024-01-15 11:20:15',
    result: 'success',
    ip: '192.168.1.101',
    riskLevel: 'medium'
  },
  {
    id: 3,
    user: '王五',
    permission: '系统管理',
    action: '尝试删除用户',
    time: '2024-01-15 15:45:30',
    result: 'failure',
    ip: '192.168.1.102',
    riskLevel: 'high'
  }
])

// 监控列配置
const monitorColumns = ref([
  { title: '用户', dataIndex: 'user', key: 'user', width: 100 },
  { title: '权限', dataIndex: 'permission', key: 'permission', width: 120 },
  { title: '操作', dataIndex: 'action', key: 'action', width: 150 },
  { title: '时间', dataIndex: 'time', key: 'time', width: 150 },
  { title: '结果', dataIndex: 'result', key: 'result', width: 80 },
  { title: 'IP地址', dataIndex: 'ip', key: 'ip', width: 120 },
  { title: '风险等级', dataIndex: 'riskLevel', key: 'riskLevel', width: 100 }
])

// 安全策略
const securityPolicies = ref([
  {
    id: 1,
    name: '登录尝试限制',
    description: '连续登录失败3次后锁定账户30分钟',
    severity: 'medium',
    status: 'active'
  },
  {
    id: 2,
    name: '权限过期检查',
    description: '定期检查用户权限是否过期',
    severity: 'high',
    status: 'active'
  },
  {
    id: 3,
    name: '异常访问监控',
    description: '监控异常时间和地点的访问行为',
    severity: 'high',
    status: 'active'
  }
])

// 安全策略列配置
const securityColumns = ref([
  { title: '策略名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '策略描述', dataIndex: 'description', key: 'description', width: 200 },
  { title: '严重程度', dataIndex: 'severity', key: 'severity', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'actions', width: 120 }
])

// 安全状态
const securityStatus = reactive({
  overall: 'good',
  vulnerabilities: 2,
  risks: 1
})

// 安全警报
const securityAlerts = ref([
  {
    id: 1,
    title: '检测到异常登录行为',
    time: '2024-01-15 16:30'
  },
  {
    id: 2,
    title: '权限使用频率异常',
    time: '2024-01-15 14:20'
  }
])

// 报告数据
const reportData = reactive({
  totalPermissions: 156,
  permissionGrowth: 12,
  activeUsers: 856,
  userGrowth: 8,
  usageRate: 75,
  usageDecline: 5,
  securityScore: 92,
  securityImprovement: 3
})

// 计算属性
const groupModalTitle = computed(() => {
  return groupForm.id ? '编辑权限组' : '新增权限组'
})

const filteredUsers = computed(() => {
  if (!userSearchText.value) return users.value
  return users.value.filter((user) => user.name.toLowerCase().includes(userSearchText.value.toLowerCase()) || user.position.toLowerCase().includes(userSearchText.value.toLowerCase()))
})

const filteredMatrixData = computed(() => {
  let result = users.value

  if (matrixFilter.department !== 'all') {
    result = result.filter((user) => user.department === matrixFilter.department)
  }

  if (matrixFilter.group !== 'all') {
    result = result.filter((user) => user.groups.includes(matrixFilter.group))
  }

  return result
})

const batchUserOptions = computed(() => {
  return users.value.map((user) => ({
    key: user.id,
    title: `${user.name} (${user.position})`,
    description: getDepartmentName(user.department)
  }))
})

// 方法
const handleTabChange = (key) => {
  activeTab.value = key
}

const getDepartmentName = (departmentId) => {
  const dept = departments.value.find((d) => d.id === departmentId)
  return dept ? dept.name : departmentId
}

const getGroupName = (groupId) => {
  const group = permissionGroups.value.find((g) => g.id === groupId)
  return group ? group.name : groupId
}

const getPermissionName = (permissionId) => {
  // 递归查找权限名称
  const findPermission = (nodes) => {
    for (const node of nodes) {
      if (node.key === permissionId) return node.title
      if (node.children) {
        const found = findPermission(node.children)
        if (found) return found
      }
    }
    return permissionId
  }
  return findPermission(permissionTree.value)
}

const getGroupPermissions = (groupId) => {
  const group = permissionGroups.value.find((g) => g.id === groupId)
  return group ? group.permissions : []
}

const getApprovalStatusColor = (status) => {
  const colors = {
    pending: 'orange',
    approved: 'green',
    rejected: 'red',
    expired: 'gray'
  }
  return colors[status] || 'default'
}

const getApprovalStatusText = (status) => {
  const texts = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝',
    expired: '已过期'
  }
  return texts[status] || status
}

const getPriorityColor = (priority) => {
  const colors = {
    high: 'red',
    medium: 'orange',
    low: 'green'
  }
  return colors[priority] || 'default'
}

const getPriorityText = (priority) => {
  const texts = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return texts[priority] || priority
}

const getRiskLevelColor = (level) => {
  const colors = {
    high: 'red',
    medium: 'orange',
    low: 'green'
  }
  return colors[level] || 'default'
}

const getRiskLevelText = (level) => {
  const texts = {
    high: '高风险',
    medium: '中风险',
    low: '低风险'
  }
  return texts[level] || level
}

const getSeverityColor = (severity) => {
  const colors = {
    high: 'red',
    medium: 'orange',
    low: 'green'
  }
  return colors[severity] || 'default'
}

const getSeverityText = (severity) => {
  const texts = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return texts[severity] || severity
}

const showAddGroupModal = () => {
  Object.assign(groupForm, {
    id: null,
    name: '',
    description: '',
    type: 'custom',
    priority: 50,
    status: 'active'
  })
  groupModalVisible.value = true
}

const editGroup = (group) => {
  Object.assign(groupForm, { ...group })
  groupModalVisible.value = true
}

const cloneGroup = (group) => {
  Object.assign(groupForm, {
    ...group,
    id: null,
    name: `${group.name} (副本)`
  })
  groupModalVisible.value = true
}

const assignPermissions = (group) => {
  selectedGroup.value = group
  checkedPermissions.value = group.permissions || []
  permissionModalVisible.value = true
}

const viewGroupMembers = (group) => {
  message.info(`查看权限组 "${group.name}" 的成员列表`)
}

const deleteGroup = (group) => {
  const index = permissionGroups.value.findIndex((g) => g.id === group.id)
  if (index !== -1) {
    permissionGroups.value.splice(index, 1)
    message.success(`权限组 "${group.name}" 已删除`)
  }
}

const showBatchAssignModal = () => {
  batchAssignModalVisible.value = true
}

const editUserPermissions = (user) => {
  selectedUser.value = user
  userGroupSelection.value = [...user.groups]
  userIndividualPermissions.value = [...user.individualPermissions]
  userRestrictions.value = {
    timeRange: null,
    ipRestriction: '',
    expireDate: null
  }
  userPermissionModalVisible.value = true
}

const viewUserPermissions = (user) => {
  message.info(`查看用户 "${user.name}" 的权限详情`)
}

const searchUsers = () => {
  // 搜索逻辑已在计算属性中处理
}

const hasPermission = (userId, permissionKey) => {
  const user = users.value.find((u) => u.id === userId)
  if (!user) return false

  // 检查个人权限
  if (user.individualPermissions.includes(permissionKey)) return true

  // 检查权限组权限
  return user.groups.some((groupId) => {
    const group = permissionGroups.value.find((g) => g.id === groupId)
    return group && group.permissions.includes(permissionKey)
  })
}

const togglePermission = (userId, permissionKey, checked) => {
  const user = users.value.find((u) => u.id === userId)
  if (!user) return

  if (checked) {
    if (!user.individualPermissions.includes(permissionKey)) {
      user.individualPermissions.push(permissionKey)
    }
  } else {
    const index = user.individualPermissions.indexOf(permissionKey)
    if (index > -1) {
      user.individualPermissions.splice(index, 1)
    }
  }

  message.success(`权限 "${getPermissionName(permissionKey)}" 已${checked ? '授予' : '移除'}`)
}

const exportPermissionMatrix = () => {
  message.info('权限矩阵导出功能开发中...')
}

const refreshMatrix = () => {
  message.info('权限矩阵刷新中...')
}

const editMatrixRow = (record) => {
  editUserPermissions(record)
}

const viewMatrixDetail = (record) => {
  viewUserPermissions(record)
}

const showApprovalConfigModal = () => {
  message.info('审批配置功能开发中...')
}

const exportApprovalData = () => {
  message.info('审批记录导出功能开发中...')
}

const approveRequest = (record) => {
  message.info(`审批申请: ${record.applicant}`)
}

const viewApprovalDetail = (record) => {
  message.info(`查看审批详情: ${record.applicant}`)
}

const editRule = (rule) => {
  message.info(`编辑规则: ${rule.title}`)
}

const updateMonitorData = () => {
  message.info('监控数据更新中...')
}

const exportMonitorData = () => {
  message.info('监控数据导出功能开发中...')
}

const showSecurityConfigModal = () => {
  message.info('安全配置功能开发中...')
}

const scanSecurityRisks = () => {
  message.info('安全风险扫描中...')
}

const editSecurityPolicy = (policy) => {
  message.info(`编辑安全策略: ${policy.name}`)
}

const testSecurityPolicy = (policy) => {
  message.info(`测试安全策略: ${policy.name}`)
}

const generateReport = () => {
  message.info('报告生成中...')
}

const exportAllReports = () => {
  message.info('报告导出功能开发中...')
}

const applyPermissionTemplate = (template) => {
  const templates = {
    basic: ['view_archives', 'report_view'],
    advanced: ['view_archives', 'edit_archives', 'karma_judgment', 'report_view'],
    admin: ['system_admin', 'user_management', 'data_export', 'audit_log', 'view_archives', 'edit_archives']
  }

  checkedPermissions.value = templates[template] || []
  message.success(`已应用${template}权限模板`)
}

const handleGroupSubmit = async () => {
  try {
    await groupFormRef.value.validate()

    if (groupForm.id) {
      // 编辑逻辑
      const index = permissionGroups.value.findIndex((g) => g.id === groupForm.id)
      if (index !== -1) {
        permissionGroups.value[index] = { ...permissionGroups.value[index], ...groupForm }
      }
      message.success('权限组更新成功')
    } else {
      // 新增逻辑
      const newGroup = {
        ...groupForm,
        id: `group_${Date.now()}`,
        memberCount: 0,
        permissionCount: 0,
        permissions: []
      }
      permissionGroups.value.push(newGroup)
      message.success('权限组创建成功')
    }

    groupModalVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleGroupCancel = () => {
  groupModalVisible.value = false
}

const handlePermissionSubmit = () => {
  if (selectedGroup.value) {
    selectedGroup.value.permissions = [...checkedPermissions.value]
    selectedGroup.value.permissionCount = checkedPermissions.value.length
    message.success('权限配置保存成功')
  }
  permissionModalVisible.value = false
}

const handlePermissionCancel = () => {
  permissionModalVisible.value = false
}

const handleUserPermissionSubmit = () => {
  if (selectedUser.value) {
    selectedUser.value.groups = [...userGroupSelection.value]
    selectedUser.value.individualPermissions = [...userIndividualPermissions.value]
    message.success('用户权限配置保存成功')
  }
  userPermissionModalVisible.value = false
}

const handleUserPermissionCancel = () => {
  userPermissionModalVisible.value = false
}

const handleBatchAssign = () => {
  message.success(`已为 ${batchAssignForm.selectedUsers.length} 个用户批量分配权限`)
  batchAssignModalVisible.value = false
}

const handleBatchAssignCancel = () => {
  batchAssignModalVisible.value = false
  Object.assign(batchAssignForm, {
    selectedUsers: [],
    groups: [],
    assignMode: 'add'
  })
}

// 图表初始化函数
let chartInstances = []
const initCharts = () => {
  nextTick(() => {
    chartInstances.forEach((chart) => chart.dispose())
    chartInstances = []

    const chartRefs = [usageChartRef, accessTrendChartRef, permissionDistributionChartRef, usageAnalyticsChartRef]

    const themeColors = {
      tooltipBg: 'rgba(30, 25, 20, 0.95)',
      borderColor: '#c2a578',
      textColor: '#dcd1c1',
      splitLine: 'rgba(194, 165, 120, 0.15)',
      chartBg: 'rgba(245, 241, 232, 0.05)'
    }

    const dataColors = ['#00BFFF', '#FFA500', '#FF69B4', '#32CD32', '#8A2BE2', '#FFD700', '#00CED1', '#FF4500']
    // DeepSkyBlue, Orange, HotPink, LimeGreen, BlueViolet, Gold, DarkTurquoise, OrangeRed

    const commonTooltip = {
      trigger: 'axis',
      backgroundColor: themeColors.tooltipBg,
      borderColor: themeColors.borderColor,
      borderWidth: 1,
      textStyle: { color: themeColors.textColor },
      borderRadius: 8,
      extraCssText: 'box-shadow: 0 4px 12px rgba(0,0,0,0.4);',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: themeColors.dark
        }
      }
    }

    const commonGrid = {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true,
      show: true,
      backgroundColor: themeColors.chartBg,
      borderColor: 'transparent'
    }

    const commonLegend = {
      bottom: 5,
      left: 'center',
      textStyle: { color: themeColors.textColor },
      itemGap: 15
    }

    const commonAxisStyle = {
      axisLabel: { color: themeColors.textColor },
      axisLine: { lineStyle: { color: themeColors.borderColor } },
      axisTick: { show: false },
      splitLine: { lineStyle: { color: themeColors.splitLine, type: 'dashed' } }
    }

    // 1. 权限使用频率
    if (usageChartRef.value) {
      const usageChart = echarts.init(usageChartRef.value)
      usageChart.setOption({
        tooltip: { ...commonTooltip, trigger: 'axis' },
        legend: commonLegend,
        grid: commonGrid,
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          ...commonAxisStyle
        },
        yAxis: { type: 'value', ...commonAxisStyle },
        series: ['查看权限', '编辑权限', '删除权限', '管理权限'].map((name, index) => ({
          name,
          type: 'bar',
          barWidth: '12%',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.1)'
          },
          emphasis: {
            focus: 'series',
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0,0,0,0.5)'
            }
          },
          data: [
            [320, 280, 350, 400, 380, 220, 180],
            [120, 100, 140, 160, 150, 80, 60],
            [30, 25, 35, 40, 38, 20, 15],
            [10, 8, 12, 15, 12, 5, 3]
          ][index],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: echarts.color.lift(dataColors[index], 0.2) },
              { offset: 1, color: dataColors[index] }
            ])
          },
          animationDelay: (idx) => idx * 10
        }))
      })
      chartInstances.push(usageChart)
    }

    // 2. 访问趋势分析
    if (accessTrendChartRef.value) {
      const trendChart = echarts.init(accessTrendChartRef.value)
      trendChart.setOption({
        tooltip: commonTooltip,
        legend: commonLegend,
        grid: commonGrid,
        xAxis: { type: 'category', boundaryGap: false, data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'], ...commonAxisStyle },
        yAxis: { type: 'value', ...commonAxisStyle },
        series: [
          {
            name: '正常访问',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            data: [50, 20, 80, 150, 200, 180, 100],
            itemStyle: { color: dataColors[0] },
            lineStyle: { width: 3, shadowColor: 'rgba(0,0,0,0.4)', shadowBlur: 10, shadowOffsetY: 5 },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: echarts.color.lift(dataColors[0], 0.1) },
                { offset: 1, color: echarts.color.lift(dataColors[0], -0.8) }
              ])
            }
          },
          { name: '异常访问', type: 'line', smooth: true, symbol: 'circle', data: [5, 2, 8, 12, 15, 18, 10], itemStyle: { color: dataColors[1], lineStyle: { width: 2, type: 'dashed' } }, lineStyle: { width: 2 } },
          { name: '拒绝访问', type: 'line', smooth: true, symbol: 'circle', data: [2, 1, 3, 5, 8, 6, 4], itemStyle: { color: dataColors[2], lineStyle: { width: 2 } }, lineStyle: { width: 2 } }
        ]
      })
      chartInstances.push(trendChart)
    }

    // 3. 权限分布统计
    if (permissionDistributionChartRef.value) {
      const distributionChart = echarts.init(permissionDistributionChartRef.value)
      distributionChart.setOption({
        tooltip: { ...commonTooltip, trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
        legend: { ...commonLegend, orient: 'vertical', left: 'left', top: 'center' },
        series: [
          {
            name: '权限类型',
            type: 'pie',
            radius: ['45%', '80%'],
            center: ['65%', '50%'],
            roseType: 'area',
            itemStyle: { borderRadius: 10, borderColor: themeColors.tooltipBg, borderWidth: 2 },
            data: [
              { value: 45, name: '基础权限', itemStyle: { color: dataColors[0] } },
              { value: 30, name: '业务权限', itemStyle: { color: dataColors[1] } },
              { value: 15, name: '管理权限', itemStyle: { color: dataColors[2] } },
              { value: 8, name: '系统权限', itemStyle: { color: dataColors[3] } },
              { value: 2, name: '超级权限', itemStyle: { color: dataColors[4] } }
            ],
            emphasis: { label: { show: true, fontSize: '18', fontWeight: 'bold' }, itemStyle: { shadowBlur: 20, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.8)' } },
            label: { show: false, position: 'center' },
            labelLine: { show: false },
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: () => Math.random() * 200
          }
        ]
      })
      chartInstances.push(distributionChart)
    }

    // 4. 使用情况分析
    if (usageAnalyticsChartRef.value) {
      const analyticsChart = echarts.init(usageAnalyticsChartRef.value)
      analyticsChart.setOption({
        tooltip: commonTooltip,
        legend: commonLegend,
        grid: commonGrid,
        xAxis: { type: 'category', data: ['1月', '2月', '3月', '4月', '5月', '6月'], ...commonAxisStyle },
        yAxis: [
          { type: 'value', name: '用户数/调用次数', ...commonAxisStyle },
          { type: 'value', name: '响应时间(ms)', ...commonAxisStyle, splitLine: { show: false } }
        ],
        series: [
          {
            name: '活跃用户',
            type: 'bar',
            data: [120, 135, 142, 158, 162, 178],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: echarts.color.lift(dataColors[0], 0.2) },
                { offset: 1, color: dataColors[0] }
              ])
            }
          },
          {
            name: '权限调用次数',
            type: 'bar',
            data: [2500, 2800, 3200, 3500, 3800, 4200],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: echarts.color.lift(dataColors[1], 0.2) },
                { offset: 1, color: dataColors[1] }
              ])
            }
          },
          {
            name: '平均响应时间',
            type: 'line',
            yAxisIndex: 1,
            smooth: true,
            symbol: 'circle',
            data: [45, 42, 38, 35, 32, 30],
            itemStyle: { color: dataColors[2], lineStyle: { width: 3, shadowColor: 'rgba(0,0,0,0.3)', shadowBlur: 8, shadowOffsetY: 4 } },
            lineStyle: { width: 3 }
          }
        ]
      })
      chartInstances.push(analyticsChart)
    }

    // Resize observer
    const resizeObserver = new ResizeObserver(() => {
      chartInstances.forEach((chart) => chart.resize())
    })

    chartRefs.forEach((ref) => {
      if (ref.value) {
        resizeObserver.observe(ref.value)
      }
    })

    onUnmounted(() => {
      resizeObserver.disconnect()
      chartInstances.forEach((chart) => chart.dispose())
    })
  })
}

onMounted(() => {
  initCharts()

  // Re-initialize charts when the relevant tabs become visible
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
        const target = mutation.target
        const isMonitorTab = target.querySelector('#usageChart') || target.querySelector('#accessTrendChart')
        const isReportsTab = target.querySelector('#permissionDistributionChart') || target.querySelector('#usageAnalyticsChart')

        if ((isMonitorTab || isReportsTab) && target.style.display !== 'none') {
          initCharts()
        }
      }
    })
  })

  const tabContentNodes = document.querySelectorAll("div[role='tabpanel']")

  if (tabContentNodes) {
    tabContentNodes.forEach((node) => {
      observer.observe(node, { attributes: true })
    })
  }

  onUnmounted(() => {
    observer.disconnect()
  })
})
</script>

<style lang="scss" scoped>
.permission-allocation-container {
  padding: 24px;

  // 页面头部
  .permission-header {
    text-align: center;
    margin-bottom: 32px;

    .header-content {
      .ancient-title {
        font-size: 32px;
        font-weight: bold;
        color: $secondary-color;
        margin-bottom: 8px;
        text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
      }

      .header-subtitle {
        font-size: 16px;
        color: $text-secondary;
        letter-spacing: 2px;
      }
    }

    .header-decoration {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 24px;
      gap: 16px;

      .decoration-line {
        width: 80px;
        height: 1px;
        background: linear-gradient(90deg, transparent, $secondary-color, transparent);
      }

      .decoration-symbol {
        font-size: 20px;
        color: $secondary-color;
        font-weight: bold;
      }
    }
  }

  // 路由信息
  .route-info {
    margin-bottom: 24px;
    padding: 12px 16px;
    border-radius: 8px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  // 选项卡区域
  .tabs-section {
    margin-bottom: 24px;

    :deep(.ant-tabs-card) {
      .ant-tabs-tab {
        border: 1px solid rgba(212, 153, 10, 0.2);
        background: rgba(212, 153, 10, 0.05);

        &.ant-tabs-tab-active {
          background: $secondary-color;
          color: white;
        }
      }
    }
  }

  // 统计卡片区域
  .stats-section {
    margin-bottom: 32px;

    .stat-card {
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      border: 1px solid rgba(212, 153, 10, 0.2);
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      gap: 16px;

      .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
      }

      .stat-content {
        flex: 1;

        .stat-title {
          font-size: 14px;
          color: $text-secondary;
          margin-bottom: 4px;
        }

        .stat-value {
          font-size: 28px;
          font-weight: bold;
          color: $primary-color;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 12px;
          color: $text-secondary;
        }
      }

      &.primary-stat .stat-icon {
        background: linear-gradient(135deg, #1890ff, #40a9ff);
      }

      &.judgment-stat .stat-icon {
        background: linear-gradient(135deg, #52c41a, #73d13d);
      }

      &.pending-stat .stat-icon {
        background: linear-gradient(135deg, #fa8c16, #ffa940);
      }

      &.online-stat .stat-icon {
        background: linear-gradient(135deg, #722ed1, #9254de);
      }
    }
  }

  // 权限组列表
  .permission-groups {
    .group-item {
      margin-bottom: 16px;
      padding: 16px;
      border: 1px solid rgba(212, 153, 10, 0.2);
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .group-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;

        .group-info {
          flex: 1;

          .group-name {
            margin: 0 0 4px 0;
            color: $primary-color;
            font-size: 16px;
            font-weight: bold;
          }

          .group-description {
            margin: 0;
            color: $text-secondary;
            font-size: 14px;
          }
        }
      }

      .group-stats {
        margin-bottom: 12px;

        .stat-item {
          text-align: center;

          .stat-number {
            font-size: 16px;
            font-weight: bold;
            color: $secondary-color;
          }

          .stat-label {
            font-size: 12px;
            color: $text-secondary;
          }
        }
      }

      .group-permissions {
        .ant-tag {
          margin-right: 4px;
        }
      }
    }
  }

  // 用户权限列表
  .user-permission-list {
    .user-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      margin-bottom: 12px;
      border: 1px solid rgba(212, 153, 10, 0.2);
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .user-info {
        display: flex;
        align-items: center;
        gap: 12px;
        flex: 1;

        .user-details {
          .user-name {
            margin: 0 0 4px 0;
            color: $primary-color;
            font-size: 16px;
            font-weight: bold;
          }

          .user-position {
            margin: 0 0 8px 0;
            color: $text-secondary;
            font-size: 14px;
          }

          .user-groups {
            .ant-tag {
              margin-right: 4px;
            }
          }
        }
      }

      .user-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  // 权限矩阵
  .matrix-controls {
    margin-bottom: 16px;
  }

  .permission-matrix {
    .matrix-header {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 12px;
    }

    .user-cell {
      display: flex;
      align-items: center;
      gap: 8px;

      .user-info {
        .user-name {
          font-weight: bold;
          color: $primary-color;
        }

        .user-role {
          font-size: 12px;
          color: $text-secondary;
        }
      }
    }

    .permission-cell {
      text-align: center;
    }
  }

  // 审批流程
  .approval-workflow {
    margin-bottom: 24px;

    .workflow-steps {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-top: 16px;

      .workflow-step {
        display: flex;
        align-items: center;
        gap: 12px;
        flex: 1;

        .step-number {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background: $secondary-color;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: bold;
        }

        .step-content {
          flex: 1;

          .step-title {
            font-weight: bold;
            color: $primary-color;
          }

          .step-description {
            font-size: 12px;
            color: $text-secondary;
            margin: 4px 0;
          }

          .step-approvers {
            margin-top: 8px;
          }
        }

        .step-connector {
          width: 40px;
          height: 2px;
          background: $secondary-color;
          margin: 0 12px;
        }
      }
    }
  }

  .approval-stats {
    margin-bottom: 24px;

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;

      .stat-card {
        padding: 16px;
        border: 1px solid rgba(212, 153, 10, 0.2);
        border-radius: 8px;
        text-align: center;

        .stat-number {
          font-size: 24px;
          font-weight: bold;
          color: $secondary-color;
        }

        .stat-label {
          font-size: 12px;
          color: $text-secondary;
        }
      }
    }
  }

  .approval-rules {
    .rules-list {
      .rule-item {
        margin-bottom: 12px;
        padding: 12px;
        border: 1px solid rgba(212, 153, 10, 0.2);
        border-radius: 8px;

        .rule-title {
          font-weight: bold;
          color: $primary-color;
          margin-bottom: 4px;
        }

        .rule-description {
          font-size: 12px;
          color: $text-secondary;
          margin-bottom: 8px;
        }

        .rule-actions {
          text-align: right;
        }
      }
    }
  }

  // 监控图表
  .usage-chart,
  .access-trend,
  .permission-distribution,
  .usage-analytics {
    h4 {
      text-align: center;
      margin-bottom: 12px;
      color: $primary-color;
      font-weight: bold;
    }
    .chart-container {
      height: 400px;
      width: 100%;
      border: 1px solid rgba(212, 153, 10, 0.2);
      border-radius: 8px;
    }
  }

  // 安全状态
  .security-status {
    margin-bottom: 24px;

    .status-indicators {
      .status-item {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;

        .indicator {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          background: #ccc;

          &.indicator-green {
            background: #52c41a;
          }

          &.indicator-yellow {
            background: #faad14;
          }

          &.indicator-red {
            background: #ff4d4f;
          }
        }

        .status-label {
          flex: 1;
          font-size: 14px;
          color: $text-secondary;
        }

        .status-value {
          font-weight: bold;
          color: $primary-color;
        }
      }
    }
  }

  .security-alerts {
    .alerts-list {
      .alert-item {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;
        padding: 12px;
        border: 1px solid rgba(255, 77, 79, 0.2);
        border-radius: 8px;
        background: rgba(255, 77, 79, 0.05);

        .alert-icon {
          color: #ff4d4f;
        }

        .alert-content {
          flex: 1;

          .alert-title {
            font-weight: bold;
            color: $primary-color;
          }

          .alert-time {
            font-size: 12px;
            color: $text-secondary;
          }
        }
      }
    }
  }

  // 报告概况
  .report-summary {
    margin-top: 24px;

    .summary-card {
      padding: 20px;
      border: 1px solid rgba(212, 153, 10, 0.2);
      border-radius: 8px;
      text-align: center;

      .summary-title {
        font-size: 14px;
        color: $text-secondary;
        margin-bottom: 8px;
      }

      .summary-value {
        font-size: 28px;
        font-weight: bold;
        color: $primary-color;
        margin-bottom: 8px;
      }

      .summary-trend {
        font-size: 12px;
        color: $text-secondary;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;
      }
    }
  }

  // 权限模板
  .permission-templates {
    margin-top: 16px;
    padding: 16px;
    border: 1px solid rgba(212, 153, 10, 0.2);
    border-radius: 8px;
    background: rgba(212, 153, 10, 0.05);

    h5 {
      margin-bottom: 8px;
      color: $primary-color;
    }
  }

  // Card样式覆盖
  :deep(.ant-card) {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(212, 153, 10, 0.2);
    border-radius: 12px;
  }

  :deep(.ant-card-head) {
    border-bottom: 1px solid rgba(212, 153, 10, 0.2);
  }

  :deep(.ant-table) {
    .ant-table-thead > tr > th {
      background: rgba(212, 153, 10, 0.1);
    }
  }
}
</style>
